package base

import (
	"fmt"
	"math/rand"
	"sort"
	"time"
)

//map基本使用
func Test1() {
	scoreMap := make(map[string]int, 8)
	scoreMap["张三"] = 60
	scoreMap["李四"] = 80
	fmt.Println("scoreMap : ", scoreMap)
	fmt.Println("scoreMap[\"张三\"] :", scoreMap["张三"])
	fmt.Printf("type of a: %T\n", scoreMap)
	fmt.Printf("len(scoreMap) :%v\n", len(scoreMap))
}

//map也支持在声明的时候填充元素
func Test2() {
	userInfo := map[string]interface{}{
		"name": "张三",
		"age":  12,
	}
	fmt.Println("userInfo: ", userInfo)
}

//判断某个键是否存在
func Test3() {
	// value, ok := map[key]
	// value:key存在返回对应的值 不存在返回nil
	// ok:bool key存在返回true 不存在返回false
	scoreMap := make(map[string]interface{})
	scoreMap["张三"] = 60
	scoreMap["李四"] = 80
	v, ok := scoreMap["张三"]
	if ok {
		fmt.Println("scoreMap[\"张三\"] ", v)
	} else {
		fmt.Println("查无此人")
	}
}

//map的遍历
func Test4() {
	scoreMap := make(map[string]interface{})
	scoreMap["张三"] = 60
	scoreMap["李四"] = 80
	scoreMap["王五"] = 100

	for k, v := range scoreMap {
		fmt.Printf("key: %v ,value: %v \n", k, v)
	}
}

//map的遍历 只遍历key
func Test5() {
	scoreMap := make(map[string]interface{})
	scoreMap["张三"] = 60
	scoreMap["李四"] = 80
	scoreMap["王五"] = 100
	//注意： 遍历map时的元素顺序与添加键值对的顺序无关。
	for k := range scoreMap {
		fmt.Printf("key: %v\n", k)
	}
}

//使用delete()函数删除键值对
func Test6() {
	//使用delete()内建函数从map中删除一组键值对，delete()函数的格式如下：
	//delete(map, key)
	/*
		其中，
		 map:表示要删除键值对的map
		 key:表示要删除的键值对的键
	*/
	scoreMap := make(map[string]interface{})
	scoreMap["张三"] = 60
	scoreMap["李四"] = 80
	scoreMap["王五"] = 100
	delete(scoreMap, "张三")
	for k, v := range scoreMap {
		fmt.Printf("key: %v ,value: %v \n", k, v)
	}
}

//按照指定顺序遍历map
func Test7() {
	rand.Seed(time.Now().UnixNano()) //初始化随机数种子
	scoreMap := make(map[string]interface{}, 200)
	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("stu%02d", i) //生成stu开头的字符串
		value := rand.Intn(100)          //生成0~99的随机整数
		scoreMap[key] = value
	}
	//取出map中的所有key存入切片keys
	keys := make([]string, 0, 200)
	for key := range scoreMap {
		keys = append(keys, key)
	}
	//对切片进行排序
	sort.Strings(keys)
	//按照排序后的key遍历map
	for _, value := range keys {
		fmt.Println(value, scoreMap[value])
	}
}

//元素为map类型的切片
func Test8() {
	sliceMap := make([]map[string]interface{}, 3)
	for index, sliceMapItem := range sliceMap {
		fmt.Printf("sliceMap index:%d , vlaue: %v \n", index, sliceMapItem)
	}
	fmt.Println("after init")
	//对切片中map元素进行初始化
	sliceMap[0] = make(map[string]interface{}, 10)
	sliceMap[0]["张三"] = "小sb"
	sliceMap[0]["李四"] = "大sb"
	sliceMap[0]["赵谦"] = "小sb"
	sliceMap[0]["孙俪"] = "大sb"
	for index, sliceMapItem := range sliceMap {
		fmt.Printf("sliceMap index:%d , vlaue: %v \n", index, sliceMapItem)
	}
}

//值为切片类型的map
func Test9() {
	mapSlice := make(map[string][]string, 3)
	fmt.Println("mapSlice ", mapSlice)
	fmt.Println("after init")
	key := "中国"
	value, ok := mapSlice[key]
	if !ok {
		value = make([]string, 0, 2)
	}
	value = append(value, "北京", "上海")
	fmt.Println("mapSlice ", mapSlice)
	mapSlice[key] = value
	fmt.Println("mapSlice ", mapSlice)
}
